package com.plus.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Map;

/**
 * @program: plus
 * @ClassName JWTUtils
 * @description: jwt帮助类
 * @author: AI
 * @create: 2023-11-02 08:25
 * @Version 1.0
 **/
@Configuration
public class JWTUtil {

    private static String SIGN;
    private static Integer expirTimeType;//枚举值参考Calendar.DATE
    private static Integer expirTime;

    @Value("${spring.security.jwtToken.sign}")
    private String SIGN_;

    @Value("${spring.security.jwtToken.expirTimeType}")
    private Integer expirTimeType_;

    @Value("${spring.security.jwtToken.expirTime}")
    private  Integer expirTime_;


    @PostConstruct
    private void init() {
        this.SIGN = SIGN_;
        this.expirTimeType = expirTimeType_;
        this.expirTime = expirTime_;
    }

    /**
     * 生成token
     */
    public static String getToken(Map<String,String> map){

        //实例化
        Calendar instance = Calendar.getInstance();
        //设置过期时间
        instance.add(expirTimeType,expirTime);

        //创建builder
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{ builder.withClaim(k,v); });
        String token = builder.withExpiresAt(instance.getTime())//指定令牌过期时间
                      .sign(Algorithm.HMAC256(SIGN));//sign
        return token;
    }

    /**
     * 验证token 合法性
     *
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取token信息方法
     */
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return verify;
    }
}


